package com.wandian.cqcsk.mvvm.mine.mywallet.txchoose;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.UserInfoBean;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.utils.BitMapUtils;
import com.mylib.libcore.utils.FileUtil;
import com.mylib.libcore.utils.GlideUtil;
import com.mylib.libcore.utils.MyGlideEngine;
import com.mylib.libcore.utils.StatusBarUtils;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.cqcsk.R;
import com.wandian.cqcsk.adapter.mine.TXChooseRecycleAdapter;
import com.wandian.cqcsk.bean.TXConfigBean;
import com.wandian.cqcsk.databinding.ActivityTxChooseBinding;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 提现选择
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_TX_CHOOSE)
public class TXChooseActivity extends BaseMVVMActivity<TXChooseViewModel> {
    private ActivityTxChooseBinding dataBinding;
    private TXChooseRecycleAdapter txChooseRecycleAdapter;
    private String amount="";
    //用户信息
    private UserInfoBean userInfoBean;
    //选择相册
    private static final int CHOOSE_PHOTO = 155;
    //权限回调
    private static final int PERMISSIONCODE = 66;
    //图片压缩地址
    private String compressImgPath;
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_tx_choose);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        initViewData();
        initRecycle();
        initClink();
        mViewModel.getAmountRatio();
        mViewModel.getUserInfo();

    }
    private void initViewData(){
        //设置状态颜色和字体黑色
        StatusBarUtils.with(this,false)
                .setIsActionBar(false)
                .clearActionBarShadow()
                .setDrawable(getResources().getDrawable(com.mylib.libcore.R.drawable.sys_color))
                .init();
        dataBinding.bindSysToolBar.toolBarTvTitle.setText("提现金额");
        userInfoBean = AppContext.getInstance().getAppPreferencesHelper().getUserInfoBean();
        notifyUserInfo();
        dataBinding.tvPayNotice.setText("1、请仔细确认到账金额，提现金额小于100元收取10%手续费。\n" +
                "2、 若填写了推荐人ID，提现金额的5%会返回给推荐人。\n" +
                "3、 申请提现后，金额到账时间1~5个工作日，节假日除外。\n" +
                "4、有关提现异常等方面的问题，请联系客服人员咨询。客服QQ:948119779 (周一-至周五10:00 ~ 19:00)");

        //提现配置
        mViewModel.listConfig.observe(this,listData->{
            if(!UIUtils.isEmpty(listData) && listData.size()>0){
                amount = listData.get(0).getAmount()+"";
                txChooseRecycleAdapter.setNewData(listData);
            }
        });

        //oos
        mViewModel.oosBean.observe(this,oosBean->{
            if(!UIUtils.isEmpty(oosBean)){
                mViewModel.upLoadImg(this, oosBean, dataBinding.ivAddSkm, compressImgPath);
            }else {
                ToastUtil.show("图片上传失败");
            }
        });

        //刷新用户信息
        mViewModel.userBean.observe(this,userBean->{
            if(!UIUtils.isEmpty(userBean)){
                this.userInfoBean = userBean;
                notifyUserInfo();
            }
        });

    }

    private void notifyUserInfo(){
        if(!UIUtils.isEmpty(userInfoBean)){
            dataBinding.tvUserCoin.setText("金币:"+userInfoBean.getGoldNum());
            dataBinding.tvUserId.setText("ID:"+userInfoBean.getId());
            dataBinding.tvUserName.setText(userInfoBean.getNickName()+"");
            if(!UIUtils.isEmpty(userInfoBean.getHeadPic())) GlideUtil.intoHeadImg(this,userInfoBean.getHeadPic(),dataBinding.ivUserHead);
        }
    }

    private void initClink(){
        dataBinding.bindSysToolBar.toolBarIvBack.setOnClickListener(v -> finish());
        dataBinding.tvBtn.setOnClickListener(v -> {
            if(!UIUtils.isEmpty(compressImgPath)){
                FileUtil.deleteFileByPath(compressImgPath);
                compressImgPath = "";
            }
            if(UIUtils.isEmpty(mViewModel.picPath)){
                ToastUtil.show("请上传收款码");
                return;
            }
            dataBinding.tvBtn.setVisibility(View.GONE);
            mViewModel.applyWithdrawal(amount,mViewModel.picPath,dataBinding.tvBtn);
        });
        //上传收款码
        dataBinding.ivAddSkm.setOnClickListener(v -> {
            if (UIUtils.isEmpty(mViewModel.picPath)) initCamer();
        });
    }

    private void initRecycle(){
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this,2);
        dataBinding.recycle.setLayoutManager(layoutManager);
        txChooseRecycleAdapter = new TXChooseRecycleAdapter(R.layout.item_tx_choose_style_one);
        dataBinding.recycle.setAdapter(txChooseRecycleAdapter);
        txChooseRecycleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                TXConfigBean bean = (TXConfigBean)baseQuickAdapter.getData().get(i);
                if(!UIUtils.isEmpty(bean)){
                    amount = bean.getAmount()+"";
                    txChooseRecycleAdapter.notifySelectItem(i);
                }
            }
        });
    }

    //修改头像
    private void initCamer() {
        boolean isAllGranted = checkPermissionAllGranted(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_SETTINGS});
        if (isAllGranted) {
            choosePhoto();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_SETTINGS}, PERMISSIONCODE);
        }
    }

    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONCODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                choosePhoto();
            }
        }
    }

    //相册
    private void choosePhoto() {
        Matisse.from(this)
                .choose(MimeType.ofAll()) // 选择 mime 的类型
                .countable(true)
                .maxSelectable(1) // 图片选择的最多数量
                .originalEnable(false)
                .maxOriginalSize(5)
                .gridExpectedSize(getResources().getDimensionPixelSize(com.wandian.setting.R.dimen.dp_120))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                .theme(com.wandian.setting.R.style.Matisse_Dracula)
                .capture(true) //是否提供拍照功能
                .autoHideToolbarOnSingleTap(true)
                .captureStrategy(new CaptureStrategy(true, mContext.getPackageName() + ".provider"))//存储到哪里
                .forResult(CHOOSE_PHOTO);// 设置作为标记的请求码
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("requestCode",requestCode+"="+resultCode);
        if (resultCode == RESULT_OK) {
            if (requestCode == CHOOSE_PHOTO) {
                if (!UIUtils.isEmpty(data)) {
                    List<Uri> mSelected = Matisse.obtainResult(data);
                    Bitmap bitmap = BitMapUtils.getBitmapFromUri(this, mSelected.get(0));
                    compressImgPath = FileUtil.getCompressFilePath(bitmap);
                    if(!UIUtils.isEmpty(compressImgPath)){
                        mViewModel.getOOSToken();
                    }else {
                        ToastUtil.show("获取本地图片失败");
                    }
                } else {
                    ToastUtil.show("上传图片失败");
                }
            }
        }
    }

}
